package com.lepu.app.usercenter.fragment;

import org.json.JSONException;
import org.json.JSONObject;

import com.core.lib.application.BaseFragment;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.ForgetPwdActivity;
import com.lepu.app.usercenter.util.UserCenterUtil;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class FragmentPwdMobile extends BaseFragment implements AsyncRequest,OnEditorActionListener {

	private static final String REQUEST_OK = "request_ok";
	private static final String REQUEST_GET_CODE = "request_get_code";

	private static final int MSG_OK_SUCCESS = 10;
	private static final int MSG_OK_FAIL = 11;

	private static final int MSG_GET_CODE_SUCCESS = 20;
	private static final int MSG_GET_CODE_FAIL = 21;
	private static final int MSG_GET_CODE_UPDATE = 22;

	private Button mGetCodeButton;

	private View mMainView = null;
	private boolean mInitDataSuccess = false;// 是否加载完数据

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.usercenter_forget_pwd_fragment_mobile, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
		mHandler.removeMessages(MSG_GET_CODE_UPDATE);
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据
				mInitDataSuccess = true;
			}
		}
	}

	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
	 */
	private void init() {
		mGetCodeButton = (Button) mMainView
				.findViewById(R.id.getCodeButton);
		Button okButton = (Button) mMainView.findViewById(R.id.okButton);

		mGetCodeButton.setTag(0);
		mGetCodeButton.setOnClickListener(mOnClickListener);
		okButton.setOnClickListener(mOnClickListener);
		
		ScrollView scrollView = (ScrollView) mMainView.findViewById(R.id.scrollView);
		scrollView.setOnTouchListener(new View.OnTouchListener() {
			
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(getActivity());
				return false;
			}
		});
		
		EditText pwdEditText2 = (EditText) mMainView.findViewById(R.id.pwdEditText2);
		pwdEditText2.setOnEditorActionListener(this);
	}

	private void requestGetResetPasswordCode() {
		EditText userEditText = (EditText) mMainView.findViewById(R.id.userEditText);
		String userContent = userEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.getResetPasswordCode(getActivity(), this,
				REQUEST_GET_CODE, userContent);
		if (flag) {
			ForgetPwdActivity.getInstance().showProgressDialog();
		}
	}

	private void requestForgetPwd() {
		EditText userEditText = (EditText) mMainView.findViewById(R.id.userEditText);
		EditText codeEditText = (EditText) mMainView.findViewById(R.id.codeEditText);
		EditText pwdEditText = (EditText) mMainView.findViewById(R.id.pwdEditText);
		EditText pwdEditText2 = (EditText) mMainView.findViewById(R.id.pwdEditText2);

		String userContent = userEditText.getText().toString().trim();
		String codeContent = codeEditText.getText().toString().trim();
		String pwdContent = pwdEditText.getText().toString().trim();
		String pwdContent2 = pwdEditText2.getText().toString().trim();

		boolean flag = UserCenterUtil.getResetPasswordByCode(getActivity(), this, REQUEST_OK, userContent,
				codeContent, pwdContent, pwdContent2);
		if(flag)
		{
			ForgetPwdActivity.getInstance().showProgressDialog();
		}
	}

	private void okSuccess() {
		new MyDialog(getActivity())
				.setMessage("新密码设置成功")
				.setCancelable(false)
				.setCanceledOnTouchOutside(false)
				.setNegativeButtonSplitImageHide(true)
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						
						MainTabActivity.jumpLogin(ForgetPwdActivity.getInstance());
						
						ForgetPwdActivity.getInstance().finish(true);
					}
				}).create(null).show();
	}

	private View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.getCodeButton:

				requestGetResetPasswordCode();
				break;
			case R.id.okButton:

				requestForgetPwd();
				break;

			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_GET_CODE_UPDATE:

				int codeText = Integer.parseInt(mGetCodeButton.getText()
						.toString());
				codeText--;

				mGetCodeButton.setText(codeText + "");
				if (codeText <= 0) {
					mHandler.removeMessages(MSG_GET_CODE_UPDATE);
					mGetCodeButton.setTag(1);
					mGetCodeButton.setText("重新获取验证码");
					mGetCodeButton.setEnabled(true);
				} else {
					mHandler.sendEmptyMessageDelayed(MSG_GET_CODE_UPDATE, 1000);
				}

				break;
			case MSG_GET_CODE_SUCCESS:
				ForgetPwdActivity.getInstance().hideProgressDialog();

				mHandler.removeMessages(MSG_GET_CODE_UPDATE);
				mGetCodeButton.setTag(0);
				mGetCodeButton.setEnabled(false);
				mGetCodeButton.setText("60");
				mHandler.sendEmptyMessageDelayed(MSG_GET_CODE_UPDATE, 1000);
				break;
			case MSG_GET_CODE_FAIL:
				ForgetPwdActivity.getInstance().hideProgressDialog();
				break;
			case MSG_OK_SUCCESS:
				ForgetPwdActivity.getInstance().hideProgressDialog();

				okSuccess();
				break;
			case MSG_OK_FAIL:
				ForgetPwdActivity.getInstance().hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_GET_CODE)) {
			String result = (String) data;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {
				mHandler.sendEmptyMessage(MSG_GET_CODE_SUCCESS);
			} else {
				mHandler.sendEmptyMessage(MSG_GET_CODE_FAIL);
			}
		} else if (object.equals(REQUEST_OK)) {
			String result = (String) data;
			int code = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				code = obj1.optInt("Status");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (code == 200) {
				mHandler.sendEmptyMessage(MSG_OK_SUCCESS);
			} else {
				mHandler.sendEmptyMessage(MSG_OK_FAIL);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_GET_CODE)) {
			mHandler.sendEmptyMessage(MSG_GET_CODE_FAIL);
		} else if (object.equals(REQUEST_OK)) {
			mHandler.sendEmptyMessage(MSG_OK_FAIL);
		}
	}
	
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_DONE:
			
			requestForgetPwd();
			break;
		}
		return true;
	}

}
